package com.mashen.jdbc;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;

public class ConnectionFactory {
	private static ConnectionFactory factory = 
			new ConnectionFactory();
	private BasicDataSource datasource;

	private ConnectionFactory() {
		Properties pro = new Properties();
		InputStream in = this.getClass()
				.getResourceAsStream("/jdbc.properties");
		try {
			pro.load(in);
			in.close();
			datasource = BasicDataSourceFactory
					.createDataSource(pro);
			System.out.println("成功创建数据源！");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static ConnectionFactory getInstance() {
		return factory;
	}

	/**
	 * 获取数据库连接
	 * 
	 * @return
	 * @throws Throwable
	 */
	public Connection getConnection() throws Throwable {
		return datasource.getConnection();
	}

	/**
	 * 关闭连接
	 * 
	 * @param conn
	 */
	public static void closeConnection(Connection conn) {
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) throws Throwable {
		// TODO Auto-generated method stub
		Connection conn=ConnectionFactory
				.getInstance().getConnection();
		System.out.println(conn);
	}

}
